package register

import (
	"fmt"
	logger "gitee.com/zaper/private-logger"
	"gitee.com/zaper/software-framework/cert_mgr"
	"gitee.com/zaper/software-framework/constant"
	"gitee.com/zaper/software-framework/middleware"
	"gitee.com/zaper/software-framework/router"
	"github.com/gin-gonic/gin"
	"github.com/go-kratos/kratos/v2"
	"github.com/go-kratos/kratos/v2/transport/http"
	"runtime/debug"
)

func InitializeRouter() {
	defer func() {
		e := recover()
		if e != nil {
			logger.Errorf("++++++++++  recover+++++++++++%s", debug.Stack())
		}
	}()

	httpRouter := router.GetHttpRouter()
	ginEngine := gin.New()
	ginEngine.Use(middleware.GetHttpMiddleWare()...)
	for _, g := range httpRouter.Groups {
		routerGroup := ginEngine.Group(g)
		for _, r := range httpRouter.Routers {
			if g == r.Group {
				switch r.Function {
				case constant.HttpGET:
					routerGroup.GET(r.Url, r.Ops...)
				case constant.HttpPUT:
					routerGroup.PUT(r.Url, r.Ops...)
				case constant.HttpPOST:
					routerGroup.POST(r.Url, r.Ops...)
				case constant.HttpDELETE:
					routerGroup.DELETE(r.Url, r.Ops...)
				default:

				}
			}
		}
	}
	err := registerGinToKts(ginEngine, httpRouter.Port).Run()
	if err != nil {
		logger.Errorf("listen server fail, err is %s", err)
	}
}

func registerGinToKts(ginEngine *gin.Engine, port string) *kratos.App {
	httpSrv := http.NewServer(
		http.Address(fmt.Sprintf(":%s", port)),
		http.TLSConfig(cert_mgr.GetServiceTlsConfig()),
	)
	httpSrv.HandlePrefix("/", ginEngine)

	return kratos.New(
		kratos.Server(httpSrv),
	)
}
